package servlet;

import dao.Shopping_cartDao;
import dao.UserDao;
import model.Shopping_cart;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

@WebServlet("/CartAddServlet.do")
public class CartAddServlet extends HttpServlet {
    private Shopping_cartDao cartDao=new Shopping_cartDao();


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        System.out.println(username);
        // 使用UserDao根据username获取user_id
        UserDao userDao = new UserDao();
        int user_id = userDao.getUserIdByUsername(username);

        if (username == null) {
            // 如果用户未登录或者 user_id 不是 Integer 类型，则重定向到登录页面或者其他处理方式
            response.sendRedirect(request.getContextPath() + "/home/login-2.jsp");
            return;
        }

        // 获取请求参数中的商品ID和数量
        request.setCharacterEncoding("UTF-8");

        // 获取表单提交的参数值
        String goods_info = request.getParameter("goods_info");
        String goods_image = request.getParameter("goods_image");
        int goods_id = Integer.parseInt(request.getParameter("goods_id"));
        double goods_price = Double.parseDouble(request.getParameter("goods_price"));


        String addedAt = LocalDateTime.now().toString();
        System.out.println("goods_info: "+goods_info+"goods_image: "+goods_image+"goods_id: "+goods_id+"goods_price: "+goods_price );
        int quantity = 1; // 默认加入购物车的数量为1，你也可以根据实际需求从页面获取具体数量

        // 获取当前时间作为添加时间


        // 创建购物车对象
        Shopping_cart cart = new Shopping_cart();
        cart.setUser_id(user_id);
        cart.setGoods_id(goods_id);
        cart.setQuantity(quantity);
        cart.setAdded_at(addedAt);

        try {
            boolean a= cartDao.addToCart(cart);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        try {
            List<Shopping_cart> cartItems = cartDao.getCartItemsByUserId(user_id);
            double cartSubtotal = 0.0;


             cartSubtotal =  goods_price * quantity;;
            double cartTotal = cartSubtotal; // Add any additional charges if applicable
            System.out.println("Cart Subtotal: " + cartSubtotal + " Cart Total: " + cartTotal  ) ;
            if (cartItems != null && !cartItems.isEmpty()) {
                for (Shopping_cart cartItem : cartItems) {
                    System.out.println("User ID: " + cartItem.getUser_id());
                    System.out.println("Goods ID: " + cartItem.getGoods_id());
                    System.out.println("Quantity: " + cartItem.getQuantity());
                    System.out.println("Added At: " + cartItem.getAdded_at());
                    System.out.println("-----------------------------------");
                }
            } else {
                System.out.println("Cart items list is empty or null.");
            }
            session.setAttribute("goods_image", goods_image);
            session.setAttribute("goods_info", goods_info);
            session.setAttribute("goods_price", goods_price);

            session.setAttribute("quantity", quantity);
            System.out.println("goods_info: "+goods_info+"goods_image: "+goods_image );
            session.setAttribute("cartItems", cartItems);
            session.setAttribute("cartSubtotal", cartSubtotal);
            session.setAttribute("cartTotal", cartTotal);

            response.sendRedirect(request.getContextPath() + "/Front/cart.jsp?subtotal=" + cartSubtotal + "&total=" + cartTotal);



        } catch (SQLException e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }
}